package com.example.Controller;

import com.example.Service.impl.MessageService;
import com.example.pojo.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/message")
public class MessageController {

    @Autowired
    private MessageService messageService;

    @GetMapping("/send/{id}")
    public ResponseEntity<byte[]> getImage(@PathVariable Long id) {
        byte[] imageData = messageService.getTest(id);
        if (imageData == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        HttpHeaders httpHeaders = new HttpHeaders();
        String fileName = getFileNameById(id); // 获取文件名，包括扩展名
        String contentType = determineContentTypeByFileName(fileName);
        httpHeaders.set("Content-Type",contentType);
        return new ResponseEntity<>(imageData, httpHeaders, HttpStatus.OK);
    }

    private String getFileNameById(Long id) {
        Message message = messageService.selectFileById(id);
        return message.getFileName();
    }

    private String determineContentTypeByFileName(String fileName) {
        if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
            return "image/jpeg";
        }if (fileName.endsWith(".png")) {
            return "image/jpeg";
        } else if (fileName.endsWith(".doc")) {
            return "application/msword";
        } else if (fileName.endsWith(".pdf")) {
            return "application/pdf";
        } else if (fileName.endsWith(".txt")) {
            return "text/plain";
        } else if (fileName.endsWith(".zip")) {
            return "application/zip";
        }
        else {
            return "application/octet-stream"; // 未知文件类型
        }
    }


    @PostMapping("/sendMessageByNameAndRecipient")
    public ResponseEntity<Map<String, Object>> sendMessageByNameAndRecipient(@RequestParam("file") MultipartFile file,
                                                                @RequestParam(value = "sender",defaultValue = "null") String sender,
                                                                @RequestParam(value = "recipient",defaultValue = "null") String recipient ) {
        try {
            // 获取文件名
            String fileName = file.getOriginalFilename();

            // 获取文件字节内容
            byte[] fileBytes = file.getBytes();
            System.out.println(file);
            // 创建 Message 实体并保存到数据库
            Message message = new Message();

            message.setFileName(fileName);

            message.setFile(fileBytes);

            message.setSendTime(LocalDateTime.now());

            message.setSender(sender);

            message.setRecipient(recipient);
            messageService.save(message);

            Map<String,Object> result = new HashMap<>();
            result.put("code","200");
            result.put("message","文件上传成功");

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", "500");
            result.put("message", "文件上传失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
}
